package avicit.bdp.dms.prm.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.dto.PythonResourceDTO;
import avicit.bdp.common.dto.upload.ResumeUploadDto;
import avicit.bdp.common.service.service.FileCommonService;
import avicit.bdp.common.service.service.FileOperateCommonService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.enums.UploadStatus;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.prm.dao.PythonResourceDao;
import avicit.bdp.dms.prm.utils.enums.PythonResStatus;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.github.pagehelper.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间：2021-04-27 15:16
 * @类说明：python包管理
 * @修改记录：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PythonResourceService extends BaseService<PythonResourceDao, PythonResourceDTO> {

    private static final Logger logger = LoggerFactory.getLogger(PythonResourceService.class);

    @Autowired
    private PythonResourceDao pythonResourceDao;
    @Autowired
    private ConvertColumnClient convertColumnClient;
    @Autowired
    private FileOperateCommonService fileOperateCommonService;
    @Autowired
    private FileCommonService fileCommonService;

    /**
     * 查询Python资源列表
     */
    public QueryRespBean<PythonResourceDTO> getPythonResList(String name,
                                                             Integer status,
                                                             Integer pageNo,
                                                             Integer pageSize) throws Exception {

        QueryRespBean<PythonResourceDTO> queryRespBean = new QueryRespBean<>();
        com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);

        Page<PythonResourceDTO> pythonResourceList = pythonResourceDao.getPythonResList(name, status);

        if (CollectionUtils.isNotEmpty(pythonResourceList)) {
            List<String> userIdList = new ArrayList<>();
            for (PythonResourceDTO pythonResource : pythonResourceList) {
                pythonResource.setStatusString(PythonResStatus.getDescByCode(pythonResource.getStatus()));

                if (StringUtils.isNotEmpty(pythonResource.getCreatedBy())) {
                    userIdList.add(pythonResource.getCreatedBy());
                }
            }

            // 根据用户ID调用平台服务返回用户名称
            Map<String, Set<String>> convertFormData = new HashMap<>();
            try{
                for (String userId : userIdList) {
                    BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, userId);
                }
            }catch (Exception e){
                logger.error("根据用户ID调用平台服务返回用户名称异常:{}", e.getMessage());
            }

            if (convertFormData.size() > 0) {
                //获取请求结果
                Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
                //循环设置Alias或Name的值
                for (PythonResourceDTO pythonResource : pythonResourceList) {
                    pythonResource.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                            pythonResource.getCreatedBy()));
                }
            }
        }
        queryRespBean.setResult(pythonResourceList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 删除python资源
     */
    public Boolean deletePythonRes(String ids) {
        CheckParaUtils.checkStringValidity(ids, logger, "没有传入待删除的id");

        String[] idArr = ids.split(Constants.COMMA);
        try{
            for (String id : idArr) {
                // 先删除文件,再删除数据表中数据
                PythonResourceDTO pythonResource = this.selectByPrimaryKey(id);
                CheckParaUtils.checkDbObjectValidity(pythonResource, logger, String.format("没有查到数据，请确保id:%s的python资源是否存在", id));

                // 判断hdfs是否存在该文件
                if (fileOperateCommonService.exists(pythonResource.getFullName())) {
                    boolean status = fileOperateCommonService.delete(pythonResource.getFullName(), false);
                    if (!status) {
                        throw new BusinessException("hdfs删除文件失败");
                    }
                }

                // 记录日志
                BdpLogUtil.log4Delete(pythonResource);

                this.deleteByPrimaryKey(pythonResource);
            }
        }catch (Exception e){
            logger.error("删除文件异常{}", e.getMessage());
        }
        return true;
    }

    /**
     * python包上传
     * @param resumeUploadDto
     */
    public void uploadPythonRes(ResumeUploadDto resumeUploadDto) {
        Long startTime = System.currentTimeMillis();
        logger.info("进入开始上传接口:{}, 参数：{}", startTime, resumeUploadDto.toString());
        fileCommonService.checkBeforeUpload(resumeUploadDto);

        try {
            fileCommonService.uploadFile(resumeUploadDto);
            Long endTime = System.currentTimeMillis();
            logger.info("结束上传时间为：{}，耗时：{}", endTime, endTime - startTime);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        }
    }

    public Map<String, String> mergeChunks(ResumeUploadDto resumeUploadDto) throws Exception {
        Map<String, String> map = fileCommonService.mergeChunks(resumeUploadDto);

        // 上传成功，写入mysql
        if(Integer.parseInt(map.get("status")) == UploadStatus.SUCCESS.getCode()){
            String fileName = resumeUploadDto.getFileName();
            Long fileSize = resumeUploadDto.getFileSize();

            // 数据表中写入数据
            String fileFullPath = resumeUploadDto.getHdfsPath() + Constants.SINGLE_SLASH + fileName;
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            PythonResourceDTO pythonResource = new PythonResourceDTO();
            pythonResource.setId(ComUtil.getId());
            pythonResource.setName(fileName);
            pythonResource.setSize(fileSize);
            pythonResource.setFileSuffix(fileSuffix);
            pythonResource.setFullName(fileFullPath);
            pythonResource.setStatus(PythonResStatus.UNINSTALLED.getCode());
            this.insert(pythonResource);

            // 记录日志
            try{
                BdpLogUtil.log4Insert(pythonResource);
            }catch (Exception e){
                logger.error("调用平台服务记录日志异常{}", e.getMessage());
            }
        }

        return map;
    }

    /**
     * 查看Python资源详情
     */
    public PythonResourceDTO getPythonResById(String id) {
        PythonResourceDTO pythonResource = this.selectByPrimaryKey(id);
        CheckParaUtils.checkDbObjectValidity(pythonResource, logger, String.format("没有查到数据，请确保id:%s的python资源是否存在", id));

        pythonResource.setStatusString(PythonResStatus.getDescByCode(pythonResource.getStatus()));
        BdpLogUtil.log4Query(pythonResource);
        return pythonResource;
    }

}
